<?php
/**
 * Created by PhpStorm.
 * User: wuz
 * Date: 2016/9/26
 * Time: 12:01
 */
namespace MyApp\Controllers\Front;

use MyApp\Controllers\Front\BaseController;
use MyApp\Models\Course;
use MyApp\Models\Select;
use Phalcon\Mvc\View;

class CourseController extends BaseController
{

    /*
     * 课程列表
     * */
    public function listAction()
    {
        $course = new Course();
        if ($this->request->isPost()) {
            $search = $this->request->getPost('search');
            $data   = $course->select('*', [
                'courseName[~]' => [$search],
            ]);
            //var_dump($data);die;
            $this->view->setVar('data', $data);
        } else {
            $data = $course->select('*', 'order by time desc limit 10'); //最新十条
            $this->view->setVar('data', $data);
        }

        $this->view->disableLevel(View::LEVEL_MAIN_LAYOUT);

    }

    /*
     * 添加课程
     * */
    public function addAction()
    {
        if ($this->request->isPost()) {
            $courseName = $this->request->getPost('courseName', 'string');
            $time       = time();
            $course     = new Course();
            $course->insert([
                'courseName' => $courseName, 'time' => $time,
            ]);
            //$this->view->setVar('product', $data);
        }
        $this->view->disableLevel(View::LEVEL_MAIN_LAYOUT);
    }

    /*
     * 编辑课程
     * */
    public function editAction()
    {
        $id     = $this->request->get('id');
        $course = new Course();
        $data   = $course->select("*", ['id' => $id]);
        $this->view->setVar('list', $data);

        //编辑课程后提交
        if ($this->request->isPost()) {
            $courseName = $this->request->getPost('courseName', 'string');
            $time       = time();
            $id         = $this->request->getPost('id', 'int');
            $course->update([
                'courseName' => $courseName, 'time' => $time,
            ], ['id' => $id]);

            $data = $course->select("*", ['id' => $id]);
            $this->view->setVar('list', $data); //将编辑完的结果重新显示到编辑界面
        }
        $this->view->disableLevel(View::LEVEL_MAIN_LAYOUT);
    }

    /*
     * 删除课程
     * */
    public function deleteAction()
    {
        if ($this->request->isPost()) {
            $course = new Course();
            $select = new Select();
            $id     = $this->request->getPost('delete');
            $course->delete(
                ['id' => $id]
            );
            $select->delete(['courseId' => $id]); //同时删除该课程的选课记录
            $this->dispatcher->forward([
                "controller" => "course",
                "action"     => "list",
            ]);
        }
        $this->view->disableLevel(View::LEVEL_MAIN_LAYOUT);
    }

}
